﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Text;
using System.EnterpriseServices;
using System.Configuration;
using Models;
using Common;
using Langben.DAL;
using Langben.BLL;
using Langben.App.Models;
using App.Codes;

namespace Langben.App.Controllers
{
    /// <summary>
    /// Loading
    /// </summary>
    public class LoadingController : BaseController
    {

        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
 
        public ActionResult Index()
        {
        
            return View();
        }
        public ActionResult CreateIndex()
        {
        
            return View();
        }
        
         /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        public ActionResult IndexSef()
        {

            return View();
        }
        /// <summary>
        /// 异步加载数据
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="rows">每页显示的行数</param>
        /// <param name="order">排序字段</param>
        /// <param name="sort">升序asc（默认）还是降序desc</param>
        /// <param name="search">查询条件</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetData(string id, int page, int rows, string order, string sort, string search)
        {

            int total = 0;
            List<Loading> queryData = m_BLL.GetByParam(id, page, rows, order, sort, search, ref total);
            return Json(new datagrid
            {
                total = total,
                rows = queryData.Select(s => new
                {
                    RowGuid = s.RowGuid
					,CreateUser = s.CreateUser
					,CreateTime = s.CreateTime
					,Type = s.Type
					,UserGuidContent = s.UserGuidContent
                   ,
                    IsDisplay = s.IsDisplay
					
                }

                    )
            });
        }
        /// <summary>
        ///  导出Excle /*在6.0版本中 新增*/
        /// </summary>
        /// <param name="param">Flexigrid传过到后台的参数</param>
        /// <returns></returns>      
        [HttpPost]
        public ActionResult Export(string id, string title, string field, string sortName, string sortOrder, string search)
        {
            string[] titles = title.Split(',');//如果确定显示的名称，可以直接定义
            string[] fields = field.Split(',');
            List<Loading> queryData = m_BLL.GetByParam(id, sortOrder, sortName, search);
             
            return Content(WriteExcle(titles, fields, queryData.ToArray()));  
        }
        /// <summary>
        /// 查看详细
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [SupportFilter]  
        public ActionResult Details(string id)
        {
            Loading item = m_BLL.GetById(id);
            return View(item);

        }
 
        /// <summary>
        /// 首次创建
        /// </summary>
        /// <returns></returns>
        [SupportFilter]
        public ActionResult Create(string id)
        { 
            
            return View();
        }
        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [SupportFilter]
        public ActionResult Create(Loading entity)
        {           
            if (entity != null && ModelState.IsValid)
            {
                string currentPerson = GetCurrentPerson();
                entity.CreateTime = DateTime.Now;
                //entity.CreatePerson = currentPerson;
              
                entity.RowGuid = Result.GetNewId();   
                string returnValue = string.Empty;
                if (m_BLL.Create(ref validationErrors, entity))
                {
                    LogClassModels.WriteServiceLog(Suggestion.InsertSucceed  + "，Loading的信息的Id为" + entity.RowGuid,"Loading"
                        );//写入日志 
                    return Json(Suggestion.InsertSucceed);
                }
                else
                { 
                    if (validationErrors != null && validationErrors.Count > 0)
                    {
                        validationErrors.All(a =>
                        {
                            returnValue += a.ErrorMessage;
                            return true;
                        });
                    }
                    LogClassModels.WriteServiceLog(Suggestion.InsertFail + "，Loading的信息，" + returnValue,"Loading"
                        );//写入日志                      
                    return Json(Suggestion.InsertFail  + returnValue); //提示插入失败
                }
            }

            return Json(Suggestion.InsertFail + "，请核对输入的数据的格式"); //提示输入的数据的格式不对 
        }
        /// <summary>
        /// 首次编辑
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns> 
        [SupportFilter] 
        public ActionResult Edit(string id)
        {
            Loading item = m_BLL.GetById(id);
            return View(item);
        }
        /// <summary>
        /// 提交编辑信息
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="collection">客户端传回的集合</param>
        /// <returns></returns>
        [HttpPost]
        [SupportFilter]
        public ActionResult Edit(string id, Loading entity)
        {
            if (entity != null && ModelState.IsValid)
            {   //数据校验
            
                string currentPerson = GetCurrentPerson();                 
                //entity.UpdateTime = DateTime.Now;
                //entity.UpdatePerson = currentPerson;
                           
                string returnValue = string.Empty;   
                if (m_BLL.Edit(ref validationErrors, entity))
                {
                    LogClassModels.WriteServiceLog(Suggestion.UpdateSucceed + "，Loading信息的Id为" + id,"Loading"
                        );//写入日志                           
                    return Json( Suggestion.UpdateSucceed); //提示更新成功 
                }
                else
                { 
                    if (validationErrors != null && validationErrors.Count > 0)
                    {
                        validationErrors.All(a =>
                        {
                            returnValue += a.ErrorMessage;
                            return true;
                        });
                    }
                    LogClassModels.WriteServiceLog(Suggestion.UpdateFail + "，Loading信息的Id为" + id + "," + returnValue, "Loading"
                        );//写入日志                           
                    return Json(Suggestion.UpdateFail  + returnValue); //提示更新失败
                }
            }
            return Json(Suggestion.UpdateFail + "请核对输入的数据的格式"); //提示输入的数据的格式不对               
          
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>   
        [HttpPost]
        public ActionResult Delete(FormCollection collection)
        {
            string returnValue = string.Empty;
            string[] deleteId = collection["query"].GetString().Split(',');
            if (deleteId != null && deleteId.Length > 0)
            { 
                if (m_BLL.DeleteCollection(ref validationErrors, deleteId))
                {
                    LogClassModels.WriteServiceLog(Suggestion.DeleteSucceed + "，信息的Id为" + string.Join(",", deleteId), "消息"
                        );//删除成功，写入日志
                    return Json("OK");
                }
                else
                {
                    if (validationErrors != null && validationErrors.Count > 0)
                    {
                        validationErrors.All(a =>
                        {
                            returnValue += a.ErrorMessage;
                            return true;
                        });
                    }
                    LogClassModels.WriteServiceLog(Suggestion.DeleteFail + "，信息的Id为" + string.Join(",", deleteId)+ "," + returnValue, "消息"
                        );//删除失败，写入日志
                }
            }
            return Json(returnValue);
        }
     
        IBLL.ILoadingBLL m_BLL;

        ValidationErrors validationErrors = new ValidationErrors();

        public LoadingController()
            : this(new LoadingBLL()) { }

        public LoadingController(LoadingBLL bll)
        {
            m_BLL = bll;
        }


        public string GetLoadingPicture()
        {
            string retstr = string.Empty;
            //
            Loading loading = m_BLL.GetById("201402120954500703125e7957c6aa4");
            string userguidcontent = loading.UserGuidContent;
            string[] arruserguid = userguidcontent.Split(';');
            SysPersonBLL sysPersonBll = new SysPersonBLL();
            retstr += "<table style='  height: 200px' align='center'>";
            retstr += "<tr>";
            for (int i = 0; i < arruserguid.Count(); i++)
            {
                string userguid = arruserguid[i];
                if (!string.IsNullOrEmpty(userguid))
                {
                    SysPerson sysPerson = sysPersonBll.GetById(userguid);
                    retstr += "<td  colspan='2'><img src='../../up/" + Convert.ToString(sysPerson.TXIMG) +
                              "' class='pictureclass' /></td>";
                }

            }
            retstr += "</tr>";
            retstr += "<tr>";
            for (int i = 0; i < arruserguid.Count(); i++)
            {
                string userguid = arruserguid[i];
                if (!string.IsNullOrEmpty(userguid))
                {
                    SysPerson sysPerson = sysPersonBll.GetById(userguid);
                    if (sysPerson.SysDepartment!=null)
                    {
                        retstr += "<td class='showname'>" + Convert.ToString(sysPerson.SysDepartment.Name) + " </td>";
                        
                    }
                    else
                    {
                        retstr += "<td class='showname'>" + Convert.ToString(sysPerson.SysDepartmentId) + " </td>";
                    }
                    retstr += "<td class='showname'>" + Convert.ToString(sysPerson.MyName) + " </td>";
                    
                  
                }

            }
            retstr += "</tr>";
            retstr += "</table>";
            //取9，有个""
            if (arruserguid.Count() > 9)
            {
               retstr+="<input style='display:none' id='picturemarquee' value='1' />";
            }
            else
            {
                retstr += "<input style='display:none' id='picturemarquee' value='0' />";
            }
            return retstr;
        }
        public string GetLoadingType()
        {
            Loading loading = m_BLL.GetById("201402120954500703125e7957c6aa4");
            return loading.Type;
        }

        public string GetUserGuidContent()
        {

            return new ClsCon().GetFieldValue("SELECT TOP 1 UserGuidContent FROM dbo.Loading");
        }


        public ActionResult GetLoadingContent()
        {
            List<Loading> loadinglist=m_BLL.GetAll().Where(s => !string.IsNullOrEmpty(s.Type) && s.IsDisplay=="是").ToList();
            List<LoadingContent> loadingContentlist=new List<LoadingContent>();
            foreach (var loading in loadinglist)
            {
                string html = GetLoadingHtml(loading);
                string title = loading.Type;
                LoadingContent content=new LoadingContent();
                content.Html = html;
                content.Title = title;
                loadingContentlist.Add(content);
            }
            return Json(loadingContentlist, JsonRequestBehavior.AllowGet);
            
        }

        public string GetLoadingHtml(Loading loading)
        {
            string retstr = string.Empty;
            //
            
            string userguidcontent = loading.UserGuidContent;
            string[] arruserguid = userguidcontent.Split(';');
            SysPersonBLL sysPersonBll = new SysPersonBLL();
            retstr += "<table style='  height: 200px' align='center'>";
            retstr += "<tr>";
            for (int i = 0; i < arruserguid.Count(); i++)
            {
                string userguid = arruserguid[i];
                if (!string.IsNullOrEmpty(userguid))
                {
                    SysPerson sysPerson = sysPersonBll.GetById(userguid);
                    retstr += "<td  colspan='2'><img src='../../up/" + Convert.ToString(sysPerson.TXIMG) +
                              "' class='pictureclass' /></td>";
                }

            }
            retstr += "</tr>";
            retstr += "<tr>";
            for (int i = 0; i < arruserguid.Count(); i++)
            {
                string userguid = arruserguid[i];
                if (!string.IsNullOrEmpty(userguid))
                {
                    SysPerson sysPerson = sysPersonBll.GetById(userguid);
                    if (sysPerson.SysDepartment != null)
                    {
                        retstr += "<td class='showname'>" + Convert.ToString(sysPerson.SysDepartment.Name) + " </td>";

                    }
                    else
                    {
                        retstr += "<td class='showname'>" + Convert.ToString(sysPerson.SysDepartmentId) + " </td>";
                    }
                    retstr += "<td class='showname'>" + Convert.ToString(sysPerson.MyName) + " </td>";


                }

            }
            retstr += "</tr>";
            retstr += "</table>";
            //取9，有个""
            if (arruserguid.Count() > 9)
            {
                retstr += "<input style='display:none' id='picturemarquee' value='1' />";
            }
            else
            {
                retstr += "<input style='display:none' id='picturemarquee' value='0' />";
            }
            return retstr;
        }
    }

    public class LoadingContent
    {
        public  string Html { get; set; }
        public  string Title { get; set; }
    }
}


